<template>
  <div v-if="showInstallPrompt" class="pwa-install-prompt">
    <el-alert
      title="安装应用"
      type="info"
      :closable="true"
      @close="dismissPrompt"
      show-icon
    >
      <div class="prompt-content">
        <p>将此应用安装到您的设备上，以获得更好的体验！</p>
        <div class="prompt-actions">
          <el-button type="primary" @click="installPWA">安装</el-button>
          <el-button @click="dismissPrompt">暂不安装</el-button>
        </div>
      </div>
    </el-alert>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'

const showInstallPrompt = ref(false)
const deferredPrompt = ref(null)

// 监听beforeinstallprompt事件
const handleBeforeInstallPrompt = (e) => {
  // 阻止Chrome 67及更早版本自动显示安装提示
  e.preventDefault()
  // 保存事件，以便稍后触发
  deferredPrompt.value = e
  // 显示自定义安装提示
  showInstallPrompt.value = true
}

// 安装PWA
const installPWA = async () => {
  if (!deferredPrompt.value) {
    return
  }
  // 显示安装提示
  deferredPrompt.value.prompt()
  // 等待用户响应提示
  const { outcome } = await deferredPrompt.value.userChoice
  console.log(`用户 ${outcome === 'accepted' ? '接受' : '拒绝'} 了安装`)
  // 清除保存的提示，因为它只能使用一次
  deferredPrompt.value = null
  showInstallPrompt.value = false
}

// 关闭提示
const dismissPrompt = () => {
  showInstallPrompt.value = false
  // 可以在这里设置本地存储，以便一段时间内不再显示提示
  localStorage.setItem('pwaInstallPromptDismissed', Date.now().toString())
}

onMounted(() => {
  // 检查用户是否已经关闭过提示
  const lastDismissed = localStorage.getItem('pwaInstallPromptDismissed')
  // 如果没有关闭过，或者距离上次关闭已经过了一周
  const showAgain = !lastDismissed || (Date.now() - parseInt(lastDismissed)) > 7 * 24 * 60 * 60 * 1000
  
  if (showAgain) {
    window.addEventListener('beforeinstallprompt', handleBeforeInstallPrompt)
  }
})

onBeforeUnmount(() => {
  window.removeEventListener('beforeinstallprompt', handleBeforeInstallPrompt)
})
</script>

<style scoped>
.pwa-install-prompt {
  position: fixed;
  bottom: 20px;
  left: 20px;
  right: 20px;
  z-index: 1000;
}

.prompt-content {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.prompt-actions {
  display: flex;
  gap: 10px;
}
</style> 